import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Link, routerRedux } from 'dva/router';
import url from 'url';
import querystring from 'querystring';
import { Card, Input, Row, Popover, Col, Icon, Select, Checkbox, Pagination, Button, Spin, Table } from 'antd';
import styles from './index.less';
import KXIcons from './Columns/KXIcons';
import { queryShopPools } from '../../services/tool';
import { searchAuctions } from '../../services/auction';
import ShopPop from './Modals/ShopPop';

const Option = Select.Option;
const Search = Input.Search;
const CheckboxGroup = Checkbox.Group;
const { Meta } = Card;
const initialState = {
  searchValue: '',
  icon: [],
  view_price_start: '',
  view_price_end: '',
  pool: undefined,
  isTmall: 0,
};

@connect(state => ({
  currentUser: state.user.currentUser,
  data: state.auction.ncAuctions,
  loading: state.auction.ncAuctionsLoading,
}))
export default class NcPools extends PureComponent {
  state = {
    shopPool: [],
    searchValue: '',
    icon: [],
    view_price_start: '',
    view_price_end: '',
    pool: undefined,
    isTmall: 0,
  }
  componentWillMount() {
    const { currentUser, data: { pagination: { current, pageSize } } } = this.props;
    const query = querystring.parse(this.props.location.search.substr(1));
    this.props.dispatch({
      type: 'auction/fetchNcAuctions',
      payload: { pageSize, currentPage: current, user_id: currentUser._id, pool: query.kxId }
    });
    queryShopPools().then(shopPool => {
      const newShopPool = [];
      shopPool.forEach(p => {
        const kxuan_url = url.parse(p.kxuan_url);
        const query = querystring.parse(kxuan_url.query);
        if (!newShopPool.find(item => item.id === query.id)) {
          newShopPool.push({...p, id: query.id});
        }
      });
      this.setState({
        shopPool: newShopPool,
      });
    });
  }
  handleSearch = (value, key) => {
    // console.log({ [key]: value });
    const { currentUser, data: { pagination: { current, pageSize } } } = this.props;
    const payload = {};
    if (this.state.searchValue) {
      payload.search = this.state.searchValue;
    } else if (this.state.icon.length > 0) {
      payload.icon = JSON.stringify(this.state.icon);
    } else if (this.state.pool) {
      payload.pool = this.state.pool;
    } else if (this.state.isTmall !== 0) {
      payload.isTmall = this.state.isTmall;
    }
    if (key === 'icon') {
      payload[key] = value && value.length > 0 ? JSON.stringify(value) : '';
    } else if (key === 'isTmall') {
      payload[key] = value === 0 ? undefined : value;
    } else {
      payload[key] = value;
    }
    this.props.dispatch({
      type: 'auction/fetchNcAuctions',
      payload: { ...payload, pageSize, currentPage: current, user_id: currentUser._id }
    });
    this.setState({ [key]: value });
  }
  clearInpVal = () => {
    if (this.state.searchValue) {
      this.setState({
        searchValue: '',
      });
      this.handleSearch('', 'search');
    }
  }
  handleClear = () => {
    this.setState(initialState, () => {
      this.handleSearch('', 'search');
    });
  }
  handlePageChange = (currentPage, pageSize) => {
    const { currentUser } = this.props;
    const { view_price_start, view_price_end } = this.state
    this.props.dispatch({
      type: 'auction/fetchNcAuctions',
      payload: { view_price_start, view_price_end, pageSize, currentPage, user_id: currentUser._id }
    });
  }

  toStorage = (val) => {
    this.props.dispatch(routerRedux.push('/fullpage/nicaiPool/storage'));
  }

  renderCard = props => {
    // console.log('props: ', props)
    return (
      <Card.Grid key={props._id}
        style={{
          width: '180px',
          height: '325px',
          padding: 0,
          boxSizing: 'border-box',
          marginRight: '22px',
          marginTop: '22px'
        }}
      >
        <div className={styles['item-auctions']} key={props._id}>
          <div className={styles['pic-box']}>
            <a href={props.detail_url} target="_blank">
              <img src={props.pic_url} alt={props.raw_title} />
            </a>
          </div>
          <div className={styles['ctx-box']}>
            <div className={styles['title']}>
              <a href={props.detail_url} target="_blank" dangerouslySetInnerHTML={{ __html: props.title }}></a>
            </div>
            <div className={styles['price']}>
              <div className={styles['num']}>
                <span>¥ <strong>{props.view_price}</strong></span>
              </div>
              <div className={styles['deal-cnt']}>{props.view_sales}</div>
            </div>
            <div className={styles['rate']}>{props.q_score}</div>
            <div className={styles['name']}>
              <div className={styles['shop']}>
                <Popover content={<ShopPop value={props}/>} placement="bottom">
                  <a href={props.shopLink} target="_blank">{props.nick}</a>
                </Popover>
              </div>
              <div className={styles['location']}>{props.item_loc}</div>
            </div>
            <div className={styles['feature-icons']}>
              <KXIcons icon={props.icon} />
            </div>
          </div>
        </div>
      </Card.Grid>
    )
  }

  handlePriceSearch = async (view_price_start, view_price_end) => {
    const { currentUser, data: { pagination: { current, pageSize } } } = this.props;    
    this.props.dispatch({
      type: 'auction/fetchNcAuctions',
      payload: { view_price_start, view_price_end, pageSize, currentPage: current, user_id: currentUser._id }
    })
  }

  render() {
    const { data, loading } = this.props;
    const { view_price_start, view_price_end } = this.state;
    // let options = [
    //   {
    //     label: '选品池', name: 'select',
    //     props: {
    //       value: 'default',
    //       dataSource: [
    //         {value: 'default', label: '不限'}
    //       ]
    //     }
    //   },
    //   {
    //     label: '选择店铺', name: 'checkbox',
    //     props: {
    //       value: '',
    //       dataSource: [
    //         {value: 'nicai', label: '尼采商家'},
    //         {value: 'gold', label: '金牌商家'},
    //         {value: 'tmall', label: '天猫'},
    //         {value: 'brands', label: '品牌'},
    //       ]
    //     }
    //   },
    //   {label: '商品标签', name: ''},
    //   {label: '商品品质',},
    //   {label: '商品价格',},
    // ]
    let checkboxGroup = [
      { label: '尼采商家', value: '1' },
      { label: '金牌卖家', value: '2' },
      { label: '天猫', value: '3' },
      { label: '品牌', value: '4' },
    ];
    let labelCheck = [
      { label: '奢饰品', value: '奢侈' },
      { label: '精品推荐', value: '推荐' },
      { label: '新品', value: '新品' },
      { label: '趋势品', value: '趋势' },
      { label: '特色商品', value: '风格' },
      { label: '新七条', value: '营销' },
    ];
    let labelBrand = [
      { label: '有优质评价', value: '5' }
    ]
    const span = {
      label: 2,
      value: 22,
    };
    return (
      <Card className={styles['nc-pools']}>
        <Row type="flex" align="middle">
          <Col span={2}>
            <h2>尼采选品池</h2>
          </Col>
          <Col span={22}>
            <div className={styles['searchBox']}>
              <Search
                size="large"
                value={this.state.searchValue}
                onChange={e => this.setState({ searchValue: e.target.value })}
                placeholder="请输入要搜索的关键字或商品链接"
                onSearch={value => this.handleSearch(value, 'search')}
                enterButton
              />
              <Icon type="close-circle" className={styles.clearInpIcon} onClick={this.clearInpVal} />
            </div>
          </Col>
        </Row>

        <div className={styles['cate']} style={{ position: 'relative' }}>
          <Row type="flex" align="middle">
            <Col span={span.label}>尼采选品池</Col>
            <Col span={20}>
              <Select
                size="small"
                style={{ width: 200 }}
                allowClear
                showSearch
                placeholder="不限"
                value={this.state.pool}
                onChange={value => this.handleSearch(value, 'pool')}>
                {this.state.shopPool.map((item, index) => <Option key={`pool${index}`} value={item.id}>{item.channel_name}</Option>)}
              </Select>
            </Col>
            <Col span={2}>
              {/*<Button onClick={this.toStorage}>申请入库</Button>*/}
            </Col>
          </Row>
          <Row type="flex" align="middle">
            <Col span={span.label}>选择店铺</Col>
            <Col span={span.value}>
              <Checkbox >尼采商家</Checkbox>
              <Checkbox >金牌卖家</Checkbox>
              <Checkbox checked={!!this.state.isTmall} onChange={e => this.handleSearch(e.target.checked ? 1 : 0, 'isTmall')}>天猫</Checkbox> 
              <Checkbox >品牌</Checkbox>
              <Checkbox >红人店</Checkbox>
            </Col>
          </Row>
          <Row type="flex" align="middle">
            <Col span={span.label}>商品标签</Col>
            <Col span={20}>
              <CheckboxGroup
                options={labelCheck}
                value={this.state.icon}
                onChange={value => this.handleSearch(value, 'icon')}
              />
            </Col>
          </Row>
          <Row type="flex" algin="middle">
            <Col span={span.label}>商品品质</Col>
            <Col span={20}>
              <CheckboxGroup
                options={labelBrand}
                value={this.state.icon}
                onChange={value => this.handleSearch(value, 'icon')}
              />
            </Col>
          </Row>
          <Row type="flex" align="middle">
            <Col span={span.label}>商品价格</Col>
            <Col span={20}>
            <span>价格：</span>
            <Input placeholder="￥" style={{ width: 90 }} size="small"
              value={view_price_start}
              onChange={(e) => {this.setState({view_price_start: e.target.value})}}
            />
            <span style={{ margin: '0 5px 0 5px' }}>-</span> 
            <Input placeholder="￥" style={{ width: 90 }} size="small"
              value={view_price_end}
              onChange={(e) => {this.setState({view_price_end: e.target.value})}}
            />
            <span style={{ margin: '0 5px 0 5px' }}></span> 
            <Button size="small"
              onClick={(e) => {this.handlePriceSearch(view_price_start, view_price_end)}}
            >确定</Button>
            </Col>
          </Row>
        </div>
        <Card className={styles['pools']} bodyStyle={{ padding: '0 0 10px 10px' }} >
          <Spin spinning={loading}>
              {data.list.length > 0 ? data.list.map(item => this.renderCard(item)) : '没有相关结果'}
          </Spin>
        </Card>
        <div style={{ marginTop: '10px', float: 'right' }}>
          <Pagination {...data.pagination} showQuickJumper showSizeChanger onChange={this.handlePageChange} />
        </div>
      </Card>
    )
  }
}
